package com.atguigu.jxc.controller;

import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.SupplierService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author huangxin
 * @description
 * @date 2020/12/2
 */
@RestController
@RequestMapping("/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;

    // 分页查询供应商
    // http://localhost:8080/supplier/list
    @PostMapping("/list")
    public Map<String, Object> getSuppliersByPageAndCondition(Integer page, Integer rows, String supplierName) {
        // 开启分页功能
        // 注意参数传递：将数据通过ThreadLocal绑定到当前线程上，传递给后续流程（dao）使用
        PageHelper.startPage(page, rows);
        PageInfo<Supplier> pageInfo = supplierService.getSuppliersByPageAndCondition(supplierName);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("rows", pageInfo.getList());
        return resultMap;
    }

    // 供应商添加或修改
    // http://localhost:8080/supplier/save?supplierId=1
    @PostMapping("/save")
    @SuppressWarnings("rawtypes")
    public ServiceVO saveOrUpdateSupplier(Integer supplierId, Supplier supplier) {
        if (Objects.isNull(supplierId)) {
            supplierService.saveSupplier(supplier);
        } else {
            supplier.setSupplierId(supplierId);
            supplierService.updateSupplierById(supplier);
        }
        return new ServiceVO(100, "请求成功");
    }

    // 删除供应商（支持批量删除）
    // http://localhost:8080/supplier/delete
    // ids: 4,6,7
    @PostMapping("/delete")
    @SuppressWarnings("rawtypes")
    public ServiceVO deleteSuppliersBatch(String ids) {
        supplierService.deleteSuppliersBatch(ids);
        return new ServiceVO(100, "请求成功");
    }

    // 获取供应商列表
    // http://localhost:8080/supplier/getComboboxList
    @PostMapping("/getComboboxList")
    public List<Map<String, Object>> getAllSuppliers() {
        return supplierService.getAllSuppliers();
    }
}
